package com.examstack.common.util;

import java.io.FileOutputStream;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.apache.poi.xwpf.usermodel.VerticalAlign;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class ExamPaperExportUtil {

	/**
	 * 设置title
	 * 
	 * @param document
	 * @param title
	 */
	public static void setTilte(XWPFDocument  document, String title) {
		XWPFParagraph p = document.createParagraph();
		setTextFontInfo(p, false, false, title, "黑体", "000000", "32", true, null, false, false, null, 0, null);
		setParagraphSpacingInfo(p, true, "100", "100", "0", "0", true, "240", STLineSpacingRule.Enum.forString("auto"));
		setParagraphAlignInfo(p, ParagraphAlignment.CENTER, TextAlignment.CENTER);

	}

	public static void setTable(XWPFDocument  doc, Integer rowSiez, Integer cowSize, Map<Integer,List<String>> cellNames){
		   // XWPFParagraph p1 = doc.createParagraph();  
	        XWPFTable table = doc.createTable(rowSiez, cowSize);  
	        // 设置上下左右四个方向的距离，可以将表格撑大  
	       
	        //ByteArrayOutputStream baos = new ByteArrayOutputStream();  
	        //List<XWPFTableCell> tableCells = table.getRow(0).getTableCells();  
	        //List<XWPFTableCell> tableCells1 = table.getRow(1).getTableCells(); 
	        //System.out.println("tableCells="+tableCells.size());  
	        //tableCells1.get(0).setText(cellNames.get(1).get(0));
	        for(int j = 0; j<rowSiez;j++){
	        /*	  tableCells.get(i)
	        	  .setText(cellNames.get(0).get(i)); */ 
	        	  for(int i = 0;i<cowSize;i++){  
	        		  setCellText(doc, getCellHight(table, j, i), cellNames.get(j).get(i));
	        	  }
	        } 
	        List<XWPFTableRow> rows = table.getRows();
	        /***行高**/
	        for (XWPFTableRow row : rows) {
	        	CTTrPr trPr = row.getCtRow().addNewTrPr();
	        	CTHeight ht = trPr.addNewTrHeight();
	        	ht.setVal(BigInteger.valueOf(540));
	        }
	        //表格属性  
	        CTTblPr tablePr = table.getCTTbl().addNewTblPr();  
	        //表格宽度  
	        CTTblWidth width = tablePr.addNewTblW();  
	        width.setW(BigInteger.valueOf(8000));  
	        setTableWidthAndHAlign(table, "8000", STJc.CENTER);
	       

	}
	/**
	 * 设置班级，姓名
	 * 
	 * @param document
	 * @param Bj
	 */
	public static void setBJ(XWPFDocument  document, String Bj) {
		Bj = Bj == null ? "工号：________    姓名：________" : Bj;
		XWPFParagraph p = document.createParagraph();
		setTextFontInfo(p, false, false, Bj, "黑体", "000000", "24", true, null, false, false, null, 0, null);
		setParagraphSpacingInfo(p, true, "0", "0", "0", "0", true, "240", STLineSpacingRule.Enum.forString("auto"));
		setParagraphAlignInfo(p, ParagraphAlignment.LEFT, TextAlignment.CENTER);
	}

	/**
	 * 设置题组名称
	 * 
	 * @param document
	 * @param qGName
	 */
	public static void setQuestionGroup(XWPFDocument  document, String qGName) {
		XWPFParagraph p = document.createParagraph();
		setTextFontInfo(p, false, false, qGName, "宋体", "000000", "21", true, null, false, false, null, 0, null);
		setParagraphSpacingInfo(p, true, "0", "0", "100", null, true, "240", STLineSpacingRule.Enum.forString("auto"));
		setParagraphAlignInfo(p, ParagraphAlignment.LEFT, TextAlignment.CENTER);
	}
	/**
	 * 换行
	 * @param doc
	 */
	public static void setOtherLine(XWPFDocument doc){
		XWPFParagraph crta = doc.createParagraph();
		XWPFRun cra = crta.createRun();
		//cra.addCarriageReturn();//增加回车换行
		cra.setText("\r");
	}

	/**
	 * 设置题名称
	 * 
	 * @param document
	 * @param qName
	 */
	public static void setQuestion(XWPFDocument  document, String qName) {
		XWPFParagraph p = document.createParagraph();
		setTextFontInfo(p, false, false, qName, "宋体", "000000", "21", false, null, false, false, null, 0, null);
		setParagraphSpacingInfo(p, true, "0", "0", "0", "0", true, "240", STLineSpacingRule.Enum.forString("auto"));
		setParagraphAlignInfo(p, ParagraphAlignment.LEFT, TextAlignment.CENTER);
	}

	/**
	 * 设置字体信息 设置字符间距信息
	 * @param p
	 * @param isInsert
	 * @param isNewLine
	 * @param content
	 * @param fontFamily
	 * @param colorVal
	 * @param fontSize
	 * @param isBlod
	 * @param underPatterns
	 * @param isItalic
	 * @param isStrike
	 * @param verticalAlign  SUPERSCRIPT上标 SUBSCRIPT下标
	 * @param position 字符位置 1磅=2
	 * @param spacingValue
	 */
	public static void setTextFontInfo(XWPFParagraph p, boolean isInsert, boolean isNewLine, String content,
			String fontFamily, String colorVal, String fontSize, boolean isBlod, UnderlinePatterns underPatterns,
			boolean isItalic, boolean isStrike, VerticalAlign verticalAlign, int position, String spacingValue) {
		XWPFRun pRun = null;
		if (isInsert) {
			pRun = p.createRun();
		} else {
			if (p.getRuns() != null && p.getRuns().size() > 0) {
				pRun = p.getRuns().get(0);
			} else {
				pRun = p.createRun();
			}
		}
		if (isNewLine) {
			pRun.addBreak();
		}
		pRun.setText(content);
		// 设置字体样式
		pRun.setBold(isBlod);
		pRun.setItalic(isItalic);
		pRun.setStrike(isStrike);
		if (underPatterns != null) {
			pRun.setUnderline(underPatterns);
		}
		pRun.setColor(colorVal);
		if (verticalAlign != null) {
			pRun.setSubscript(verticalAlign);
		}
		pRun.setTextPosition(position);

		CTRPr pRpr = null;
		if (pRun.getCTR() != null) {
			pRpr = pRun.getCTR().getRPr();
			if (pRpr == null) {
				pRpr = pRun.getCTR().addNewRPr();
			}
		} else {
			// pRpr = p.getCTP().addNewR().addNewRPr();
		}
		// 设置字体
		CTFonts fonts = pRpr.isSetRFonts() ? pRpr.getRFonts() : pRpr.addNewRFonts();
		fonts.setAscii(fontFamily);
		fonts.setEastAsia(fontFamily);
		fonts.setHAnsi(fontFamily);

		// 设置字体大小
		CTHpsMeasure sz = pRpr.isSetSz() ? pRpr.getSz() : pRpr.addNewSz();
		sz.setVal(new BigInteger(fontSize));

		CTHpsMeasure szCs = pRpr.isSetSzCs() ? pRpr.getSzCs() : pRpr.addNewSzCs();
		szCs.setVal(new BigInteger(fontSize));

		/*
		 * if(spacingValue!=null){ //设置字符间距信息 CTSignedTwipsMeasure
		 * ctSTwipsMeasure=pRpr.isSetSpacing()?pRpr.getSpacing():
		 * pRpr.addNewSpacing(); ctSTwipsMeasure.setVal(new
		 * BigInteger(spacingValue)); }
		 */
	}
    //设置表格高度    
    private static XWPFTableCell getCellHight(XWPFTable xTable,int rowNomber,int cellNumber){    
        XWPFTableRow row = null;    
        row = xTable.getRow(rowNomber);    
        row.setHeight(300);    
        XWPFTableCell cell = null;    
        cell = row.getCell(cellNumber);    
        return cell;    
    }    
    /**
     * 表格的总宽度
     * @param table
     * @param width
     * @param enumValue
     */
	public static void setTableWidthAndHAlign(XWPFTable table, String width,
			STJc.Enum enumValue) {
		CTTblPr tblPr = getTableCTTblPr(table);
		CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr
				.addNewTblW();
		if (enumValue != null) {
			CTJc cTJc = tblPr.addNewJc();
			cTJc.setVal(enumValue);
		}
		tblWidth.setW(new BigInteger(width));
		tblWidth.setType(STTblWidth.DXA);
	}
	/**
	 * @Description: 得到Table的CTTblPr,不存在则新建
	 */
	public static CTTblPr getTableCTTblPr(XWPFTable table) {
		CTTbl ttbl = table.getCTTbl();
		CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl
				.getTblPr();
		return tblPr;
	}
	
	/**
	 * 
	 * @Description: 得到Cell的CTTcPr,不存在则新建
	 */
	public static CTTcPr getCellCTTcPr(XWPFTableCell cell) {
		CTTc cttc = cell.getCTTc();
		CTTcPr tcPr = cttc.isSetTcPr() ? cttc.getTcPr() : cttc.addNewTcPr();
		return tcPr;
	}
	/**
	 * @Description: 设置列宽和垂直对齐方式
	 */
	public static void setCellWidthAndVAlign(XWPFTableCell cell, String width,
			STTblWidth.Enum typeEnum, STVerticalJc.Enum vAlign) {
		CTTcPr tcPr = getCellCTTcPr(cell);
		CTTblWidth tcw = tcPr.isSetTcW() ? tcPr.getTcW() : tcPr.addNewTcW();
		if (width != null) {
			tcw.setW(new BigInteger(width));
		}
		if (typeEnum != null) {
			tcw.setType(typeEnum);
		}
		if (vAlign != null) {
			CTVerticalJc vJc = tcPr.isSetVAlign() ? tcPr.getVAlign() : tcPr
					.addNewVAlign();
			vJc.setVal(vAlign);
		}
	}


    /**  
     *   
     * @param xDocument  
     * @param cell  
     * @param text  
     * @param bgcolor  
     * @param width  
     */    
	private static void setCellText(XWPFDocument xDocument, XWPFTableCell cell,    
            String text) {  
            CTP ctp = CTP.Factory.newInstance();    
            XWPFParagraph p = new XWPFParagraph(ctp, cell);    
            p.setAlignment(ParagraphAlignment.CENTER);    
    		p.setVerticalAlignment(TextAlignment.CENTER);
            XWPFRun run = p.createRun();    
            run.setBold(true);
            run.setColor("000000");    
            run.setFontSize(10);   
            run.setText(text);    
            CTRPr rpr = run.getCTR().isSetRPr() ? run.getCTR().getRPr() : run.getCTR().addNewRPr();    
            CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();    
            fonts.setAscii("黑体");    
            fonts.setEastAsia("黑体");    
            fonts.setHAnsi("黑体");   
            cell.setParagraph(p);    
    } 
    @SuppressWarnings("unused")
	private static void setCellText(XWPFDocument xDocument, XWPFTableCell cell) {  
            CTP ctp = CTP.Factory.newInstance();    
            XWPFParagraph p = new XWPFParagraph(ctp, cell);    
            p.setAlignment(ParagraphAlignment.CENTER);    
            XWPFRun run = p.createRun();
            run.setBold(true);
            run.setColor("000000");    
            run.setFontSize(20);    
            CTRPr rpr = run.getCTR().isSetRPr() ? run.getCTR().getRPr() : run.getCTR().addNewRPr();    
            CTFonts fonts = rpr.isSetRFonts() ? rpr.getRFonts() : rpr.addNewRFonts();    
            fonts.setAscii("黑体");    
            fonts.setEastAsia("黑体");    
            fonts.setHAnsi("黑体");   
            cell.setParagraph(p);    
    } 
	public static void addNewPage(XWPFDocument document, BreakType breakType) {
		XWPFParagraph xp = document.createParagraph();
		xp.createRun().addBreak(breakType);
	}

	public static void saveDocument(XWPFDocument document, String savePath) throws Exception {
		FileOutputStream fos = new FileOutputStream(savePath);
		document.write(fos);
		fos.close();
	}

	/**
	 *  设置段落间距信息
	 *  一行=100 一磅=20
	 * @param p 		         文档对象
	 * @param isSpace      是否设置行间距
	 * @param before	         段前
	 * @param after	                     段后
	 * @param beforeLines  段前行数
	 * @param afterLines   段后行数
	 * @param isLine
	 * @param line
	 * @param lineValue
	 */
	public static void setParagraphSpacingInfo(XWPFParagraph p, boolean isSpace, String before, String after,
			String beforeLines, String afterLines, boolean isLine, String line, STLineSpacingRule.Enum lineValue) {
		CTPPr pPPr = null;
		if (p.getCTP() != null) {
			if (p.getCTP().getPPr() != null) {
				pPPr = p.getCTP().getPPr();
			} else {
				pPPr = p.getCTP().addNewPPr();
			}
		}
		CTSpacing pSpacing = pPPr.getSpacing() != null ? pPPr.getSpacing() : pPPr.addNewSpacing();
		if (isSpace) {
			// 段前磅数
			if (before != null) {
				pSpacing.setBefore(new BigInteger(before));
			}
			// 段后磅数
			if (after != null) {
				pSpacing.setAfter(new BigInteger(after));
			}
			// 段前行数
			if (beforeLines != null) {
				pSpacing.setBeforeLines(new BigInteger(beforeLines));
			}
			// 段后行数
			if (afterLines != null) {
				pSpacing.setAfterLines(new BigInteger(afterLines));
			}
		}
		if (isLine) {
			if (line != null) {
				pSpacing.setLine(new BigInteger(line));
			}
			if (lineValue != null) {
				pSpacing.setLineRule(lineValue);
			}
		}
	}

	/**
	 *  设置段落对齐
	 * @param p
	 * @param pAlign   设置左右居中
	 * @param valign   设置上下居中
	 */
	public static void setParagraphAlignInfo(XWPFParagraph p, ParagraphAlignment pAlign, TextAlignment valign) {
		p.setAlignment(pAlign);
		p.setVerticalAlignment(valign);
	}

}
